package io.kiki.stack.http.feign.SpringMvcContract;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * This factory bean creates {@link RefreshableUrl} instance as per the applicable
 * configurations.
 */
public class RefreshableUrlFactoryBean implements FactoryBean<RefreshableUrl>, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private String contextId;

    private RefreshableUrl refreshableUrl;

    @Override
    public Class<?> getObjectType() {
        return RefreshableUrl.class;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public RefreshableUrl getObject() {
        if (refreshableUrl != null) {
            return refreshableUrl;
        }

        FeignClientProperties properties = applicationContext.getBean(FeignClientProperties.class);
        if (Objects.isNull(properties.getConfig())) {
            return new RefreshableUrl(null);
        }
        FeignClientProperties.FeignClientConfig configuration = properties.getConfig().get(contextId);
        if (Objects.isNull(configuration) || !StringUtils.hasText(configuration.getUrl())) {
            return new RefreshableUrl(null);
        }

        refreshableUrl = new RefreshableUrl(FeignClientsRegistrar.getUrl(configuration.getUrl()));
        return refreshableUrl;
    }

    public void setContextId(String contextId) {
        this.contextId = contextId;
    }

}
